package bsh.dyn;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import org.objectweb.asm.MethodVisitor;

import bsh.CompilationState;
import bsh.CompilationUnit;
import bsh.CompiledScript;
import bsh.exception.CompilationFailedException;

/**
 * {@link Invocable} that calls a {@link Method} through reflection. It is not compilable, but the {@link AdaptedInvocable} can be used
 * 
 * @author takeshi
 */
public class MethodInvocable implements Invocable {

    private final Method method;

    /**
     * C'tor
     * 
     * @param method {@link Method}
     */
    public MethodInvocable(Method method) {
        super();
        this.method = method;
    }

    /**
     * {@inheritDoc}
     */
    public Object invoke(CompiledScript script, Object target, Object[] parameters) throws Throwable {
        try {
            return method.invoke(target, parameters);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    /**
     * {@inheritDoc}
     */
    public DeclaredParameterType[] getParameterTypes() {
        return Invocables.toDeclaredParameters(this.method.getParameterTypes());
    }

    /**
     * {@inheritDoc}
     */
    public boolean isVarargs() {
        return this.method.isVarArgs();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return this.method.toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return this.method.getName().hashCode() + Arrays.hashCode(this.method.getParameterTypes());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof MethodInvocable)) {
            return false;
        }
        MethodInvocable other = (MethodInvocable) obj;
        return this.method.getName().equals(other.method.getName())
                && Arrays.equals(this.method.getParameterTypes(), other.method.getParameterTypes());
    }

    /**
     * {@inheritDoc}
     */
    public boolean isCompilable() {
        return false;
    }

    /**
     * @return the {@link Method}
     */
    public Method getMethod() {
        return this.method;
    }

    /**
     * {@inheritDoc}
     */
    public void generateBytecode(MethodVisitor visitor, CompilationUnit unit, CompilationState state) throws CompilationFailedException {
        throw new IllegalStateException("cannot be compiled");
    }

}
